<template>
    <div class="container app-container">
        <div class="title" style="margin:20px 0 20px 0;height:20px;line-height:20px;border-left:1px solid #CCC;text-indent:15px;">${title}</div>
        <div class="form">
            <el-form ref="form" :model="form" :rules="rules" label-width="150px">

                <!-- 遍历字段 -->
                <#list columns as col>
                    <el-row>
                        <el-col :span="8">
                            <#if (col.type == "string")>
                                <el-form-item label="${col.description}" prop="${col.name}">
                                    <el-input v-model="form.${col.name}" placeholder="请输入" show-word-limit/>
                                </el-form-item>
                            </#if>
                            <#if (col.type == "number")>
                                <el-form-item label="${col.description}" prop="${col.name}">
                                    <el-input-number v-model="form.${col.name}" :min="1" :max="10"></el-input-number>
                                </el-form-item>
                            </#if>
                            <#if (col.type == "textarea")>
                                <el-form-item label="${col.description}" prop="${col.name}">
                                    <el-input v-model="form.${col.name}" style="width: 500px;" type="textarea" placeholder="请输入内容" maxlength="500" size="medium" show-word-limit/>
                                </el-form-item>
                            </#if>
                            <#if (col.type == "select")>
                                <el-form-item label="${col.description}" prop="${col.name}">
                                    <el-select
                                            v-model="form.${col.name}" placeholder="请选择"
                                            <#if (col.multiple??)> multiple</#if>
                                            <#if (col.filterable??)> filterable</#if>
                                    >
                                        <el-option v-for="item in ${col.name}List" :key="dict.value" :label="dict.label" :value="dict.value" />
                                    </el-select>
                                </el-form-item>
                            </#if>
                            <#if (col.type == "date")>
                                <el-form-item label="${col.description}" prop="${col.name}">
                                    <el-date-picker v-model="form.${col.name}" type="date" placeholder="选择日期"></el-date-picker>
                                </el-form-item>
                            </#if>
                            <!-- 日期范围选择 -->
                            <#if (col.type == "dateRange")>
                                <el-form-item label="${col.description}" prop="${col.name}">
                                    <el-date-picker
                                        v-model="form.${col.name}"
                                        type="daterange"
                                        range-separator="-"
                                        start-placeholder="开始日期"
                                        end-placeholder="结束日期"
                                        @change="handle${col.name}"
                                  ></el-date-picker>
                                </el-form-item>
                            </#if>
                            <!-- 日期+时间范围选择 -->
                            <#if (col.type == "dateTimeRange")>
                                <el-form-item label="${col.description}" prop="${col.name}">
                                    <el-date-picker
                                            v-model="form.${col.name}"
                                            value-format="yyyy-MM-dd HH:mm:ss"
                                            type="datetimerange"
                                            range-separator="-"
                                            start-placeholder="开始日期"
                                            end-placeholder="结束日期"
                                            :default-time="['00:00:00', '23:59:59']"
                                            @change="handle${col.name}"
                                    ></el-date-picker>
                                </el-form-item>
                            </#if>
                            <!-- 图片上传 -->
                            <#if (col.type == "image")>
                                <el-form-item label="${col.description}" prop="${col.name}">
                                  <div style="width:800px">
                                    <image-upload
                                      :file-size="fileSize"
                                      :file-type="fileType"
                                      :limit="${col.limit}"
                                      :tip="'${col.imgTips}'"
                                      :value="form.${col.name}"
                                      input-type="json"
                                      @input="handleUpload${col.name}"
                                    ></image-upload>
                                  </div>
                                </el-form-item>
                            </#if>
                        </el-col>
                    </el-row>
                </#list>
                <!-- 遍历字段 -->

            </el-form>
        </div>

        <div class="footer">
            <el-button size="mini" type="primary" @click="submitForm" class="submit-btn" v-preventReClick>确认保存</el-button>
        </div>

    </div>
</template>

<script>
    // 导入接口方法
    import { ${addApiMethod}, ${updateApiMethod}, ${fetchApiMethod} } from '${apiPath}';

    export default {
        // 要改命名，比如课程编辑页可以叫 courseAddOrUpdate
        name: '${name}',
        dicts: [],
        components: {},
        data() {
            return {
                // 标题
                title: '${title}',
                // 初始化 id 为 null
                id: null,
                // 初始化 isEdit 为 false
                isEdit: false,
                <#if (hasUpload)>
                // 图片大小单位M
                fileSize: 5,
                // 图片类型
                fileType: ['jpg', 'jpeg', 'png', 'bmp'],
                </#if>
                // 表单参数
                form: {
                    <#list columns as col>
                        <#if (col.type == "select" && col.multiple??)>
                            ${col.name}: [],
                        <#elseif (col.type == "string")>
                            ${col.name}: '',
                        <#elseif (col.type == "number")>
                            ${col.name}: 0,
                        <#else>
                            ${col.name}: null,
                        </#if>
                    </#list>
                },
                // 表单校验
                rules: {
                    <#list columns as col>
                        <#if (col.required??)>
                            <#if (col.type == "mail")>
                            ${col.name}: [
                                { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                                { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                            ],
                            <#else>
                            ${col.name}: [
                                { required: true, message: '${col.description}不能为空', trigger: 'blur' },
                            ],
                            </#if>
                        </#if>
                    </#list>
                },
            };
        },
        created() {
            // 通过 $route.params 获取路由参数
            this.id = this.$route.query.id ? this.$route.query.id : null;
            console.log(this.id);
            // 判断是否存在 id 参数
            this.isEdit = !!this.id;
            if (this.isEdit) {
                // 如果存在 id 参数，则说明当前页面是修改状态
                // 可以根据 id 参数获取需要修改的数据
                this.getDetail(this.id);
            } else {
                // 如果不存在 id 参数，则说明当前页面是新增状态
            }
        },
        mounted() {},
        methods: {
            // 表单重置
            reset() {
                this.form = {
                    <#list columns as col>
                        <#if (col.type == "select" && col.multiple??)>
                            ${col.name}: [],
                        <#elseif (col.type == "string")>
                            ${col.name}: '',
                        <#elseif (col.type == "number")>
                            ${col.name}: 0,
                        <#else>
                            ${col.name}: null,
                        </#if>
                    </#list>
                };
                this.resetForm('form');
            },

            /** 获取form表单数据 */
            async getDetail(id) {
                try {
                    const res = await ${fetchApiMethod}(id);
                    if (res.code == 200) {
                        const {
                            <#list columns as col>${col.name},</#list>
                        } = res.data;

                        this.form = {
                            <#list columns as col>
                                ${col.name}<#if (col.multiple??)>${":" + col.name + ".split(',')"}</#if>,
                            </#list>
                        };
                    }
                } catch (err) {
                    console.error(err);
                }
            },

            /** 提交按钮 */
            submitForm() {
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        if (this.id != null) {
                            this.$confirm('确定修改当前内容', '确定保存', {
                                confirmButtonText: '确定',
                                cancelButtonText: '取消',
                                type: 'warning',
                            })
                                .then(() => {
                                    // 调用修改接口
                                    this.handleUpdate();
                                })
                                .catch(() => {});
                        } else {
                            this.$confirm(
                                '确定发布',
                                '确定发布',
                                {
                                    confirmButtonText: '确定',
                                    cancelButtonText: '取消',
                                    type: 'warning',
                                },
                            )
                                .then(() => {
                                    // 调用新增接口
                                    this.handleAdd();
                                })
                                .catch(() => {});
                        }
                    }
                });
            },

            /** 新增 */
            handleAdd() {
                let saveData = {
                    ...this.form,
                };
                // 预处理接口传参
                <#list columns as col>
                    <#if (col.multiple??)>
                        saveData.${col.name} = saveData.${col.name}.join(',');
                    </#if>
                </#list>
                // saveData.thumbnailUrl = process.env.VUE_APP_IMG_PRE + saveData.thumbnailUrl;
                this.$modal.loading('正在保存...');

                ${addApiMethod}(saveData)
                    .then((res) => {
                        if (res.code == 200) {
                            this.close();
                        } else {
                            this.$message.error(res.message);
                        }
                        this.$modal.closeLoading();
                    })
                    .catch((err) => {
                        this.$modal.closeLoading();
                    });
            },

            /** 更新 */
            handleUpdate() {
                let saveData = {
                    ...this.form,
                };
                // 预处理接口传参
                saveData.id = this.id;
                <#list columns as col>
                    <#if (col.multiple??)>
                        saveData.${col.name} = saveData.${col.name}.join(',');
                    </#if>
                </#list>
                this.$modal.loading('正在保存...');

                ${updateApiMethod}(saveData)
                    .then((res) => {
                        if (res.code == 200) {
                            this.close();
                        }
                        this.$modal.closeLoading();
                    })
                    .catch((err) => {
                        this.$modal.closeLoading();
                    });
            },
        <#list columns as col>
            <#if (col.type == "image")>
            handleUpload${col.name}(value) {
                if(value && value.length > 0) {
                    this.form.${col.name} = JSON.parse(value).join(',');
                }
            },
            <#elseif (col.type == "dateRange" || col.type == "dateTimeRange")>
            handle${col.name}(value) {
                // TODO 在此处处理时间时间转换
                // 示例：
                // this.form.corpIdentityStart = value[0];
                // this.form.corpIdentityEnd = value[1];
                console.log('change', value);
            },
            </#if>
        </#list>

            /** 关闭按钮 */
            close() {
                // 跳转地址 和 携带参数
                const obj = {
                    path: <#if (backUrl??)>'${backUrl}'<#else>''</#if>,
                    query: {
                        t: Date.now(),
                        pageNum: this.$route.query.pageNum
                    },
                };
                this.$tab.closeOpenPage(obj).then(() => {
                    this.$tab.refreshPage(obj);
                });
            },
        },
    };
</script>

<style lang="scss" scoped>
    .container { position: relative; }
    .submit-btn { position: fixed; bottom: 10px; left: 50%;}
</style>
